package com.jason.exp.service.impl;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import javax.annotation.Resource;

import com.jason.exp.api.proto.RegionDto;
import com.jason.exp.utils.BeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jason.exp.entity.Region;
import com.jason.exp.exception.ServiceException;
import com.jason.exp.mapper.RegionMapper;
import com.jason.exp.service.RegionService;

@Service
public class RegionServiceImpl implements RegionService {
	
	static Logger logger = LoggerFactory.getLogger(RegionServiceImpl.class);

	@Resource
	private RegionMapper regionMapper;
	
	static Cache<Integer, Region> regionCache = CacheBuilder.newBuilder().maximumSize(1000).build();

	@Override
	public List<RegionDto> findAll() {
		List<Region> regions = regionMapper.findAll();
		List<RegionDto> regionDtos = BeanMapper.mapList(regions, RegionDto.class);
		return regionDtos;
	}

	@Override
	public RegionDto findById(Integer id) {
		if (id == null) {
			throw new ServiceException();
		}
		Region region = null;
		//1、从数据库或缓存中获取地区信息
		try {
			region = regionCache.get(id, new Callable<Region>() {
				@Override
				public Region call() throws Exception {
					logger.info("load region from db");
					return regionMapper.findById(id);
				}
			});
		} catch (ExecutionException e) {
			logger.error(e.getMessage());
			throw new ServiceException();
		}
		//2、查询地区的下级地区
		List<Region> regions = regionMapper.findByParentId(region.getId());
		RegionDto regionDto = RegionDto.fromRegion(region, regions);
		return regionDto;
	}

}
